package menu

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateMenuLogic {
	return &CreateMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateMenuLogic) CreateMenu(req *types.MenuCreateReq) (resp *types.Empty, err error) {

	query := l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityMenu{})

	// 检查名称是否重复
	var existMenu model.CsCommunityMenu
	if err = query.Session(&gorm.Session{}).Where("name = ?", req.Name).Find(&existMenu).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if existMenu.ID != 0 {
		return nil, e.NewGrpcErr(codes.AlreadyExists, e.MenuNameExists)
	}

	// 创建专栏
	newMenu := &model.CsCommunityMenu{
		Name:        req.Name,
		Publish:     false, // 默认不发布
		Description: req.Description,
	}

	if err = query.Create(newMenu).Error; err != nil {
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	return &types.Empty{}, nil
}
